<template>
  <div class="app-container home">
    <!-- 顶部操作栏 -->
    <el-row :gutter="20" class="operate-bar">
      <el-button @click.stop="() => router.back()">
        返回
      </el-button>
      <el-col :span="12">
        <div class="button-group-start">
          <el-button @click.stop="chooseSuject">科目选择</el-button>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="button-group-end">
          <el-button type="primary" @click="handleSave">保存题目</el-button>
          <!-- <el-button>题目预览</el-button> -->
        </div>
      </el-col>
    </el-row>

    <!-- 新增科目选择弹窗 -->
    <el-dialog 
      v-model="isChooseSubjectVisible" 
      title="科目选择" 
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form label-width="80px">
        <!-- 省市级联选择器 -->
        <el-form-item label="地区">
          <el-cascader
            v-model="selectedArea"
            :options="areaOptions"
            :props="{ expandTrigger: 'hover' }"
            clearable
          />
        </el-form-item>
    
        <!-- 年级选择器 -->
        <el-form-item label="年级">
          <el-select v-model="selectedGrade" placeholder="请选择年级" clearable>
            <el-option
              v-for="grade in gradeOptions"
              :key="grade"
              :label="grade"
              :value="grade"
            />
          </el-select>
        </el-form-item>
    
        <!-- 科目选择器 -->
        <el-form-item label="科目">
          <el-select v-model="selectedSubject" placeholder="请选择科目" clearable>
            <el-option
              v-for="subject in subjectOptions"
              :key="subject"
              :label="subject"
              :value="subject"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-row :gutter="20" class="main-layout">
      <!-- 左侧题型选择 -->
      <el-col :sm="24" :lg="6">
        <el-card class="question-type-card">
          <template #header>
            <div class="card-title">题型选择</div>
          </template>
          <el-tabs 
            v-model="currentQuestionType" 
            tab-position="left" 
            class="vertical-tabs"
          >
            <el-tab-pane name="choice" label="选择题" />
            <el-tab-pane name="blank" label="填空题" />
            <el-tab-pane name="answer" label="简答题" />
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 右侧题目配置 -->
      <el-col :sm="24" :lg="18">
        <el-card class="question-config-card">
          <!-- 基础配置 -->
          <div class="base-config">
            <div class="steps">         
                   <el-button icon="el-icon-arrow-left"  :disabled="currentQuestionIndex == 0"
                    @click.stop="currentQuestionIndex--"
                   >上一题</el-button>
                   <el-button icon="el-icon-arrow-right"
                   :disabled="route.query.mode == 'edit' && currentQuestionIndex == questionList.length - 1" 
                    @click.stop="addQuestion"
                   >下一题</el-button>
            </div>
            <h3 class="section-title">
              基础配置 - 
              第{{ currentQuestionIndex + 1 }}题
            </h3>
            <el-form label-width="120px">
              <el-form-item label="题目题干">
                <el-input v-model="questionList[currentQuestionIndex].name" type="textarea" :rows="3" />
              </el-form-item>
              <el-form-item label="题目说明">
                <el-input v-model="questionList[currentQuestionIndex].description" type="textarea" :rows="2" />
              </el-form-item>
            </el-form>
          </div>

          <!-- 选择题配置 -->
          <div v-if="currentQuestionType === 'choice'" class="choice-options">
            <h3 class="section-title">选项配置</h3>
            <div class="options-list">
              <el-checkbox-group  v-if="questionList[currentQuestionIndex].isMultiple" v-model="questionList[currentQuestionIndex].multipleAnswers">
                <div
                v-for="(option, index) in question.options" 
                :key="index" 
                class="option-item"
              >
                <div class="option-selector">                 
                  <el-checkbox
                    label=""
                    :key="option.value"
                    :value="option.value"
                  />
                </div>
                <el-input 
                  v-model="option.label" 
                  :prefix="`选项 ${String.fromCharCode(65 + index)}`"
                  class="option-input"
                />
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  circle 
                  class="delete-btn"
                  @click="removeOption(index)"
                />
              </div>
              </el-checkbox-group>
              <el-radio-group  v-if="!questionList[currentQuestionIndex].isMultiple" v-model="questionList[currentQuestionIndex].singleAnswer">
                <div
                v-for="(option, index) in questionList[currentQuestionIndex].options" 
                :key="index" 
                class="option-item"
              >
                <div class="option-selector">
                  <el-radio                 
                    label=""
                    :key="option.value"
                    :value="option.value"
                  />             
                </div>
                <el-input 
                  v-model="option.label" 
                  :prefix="`选项 ${String.fromCharCode(65 + index)}`"
                  class="option-input"
                />
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  circle 
                  class="delete-btn"
                  @click="removeOption(index)"
                />
              </div>
              </el-radio-group>
              
            </div>
          
            <div class="option-actions">
              <el-button type="primary" @click="addOption">添加选项</el-button>
              <el-radio-group v-model="questionList[currentQuestionIndex].isMultiple">
                <el-radio :label="false">单选题</el-radio>
                <el-radio :label="true">多选题</el-radio>
              </el-radio-group>
            </div>
          </div>

          <!-- 参考答案 -->
          <div class="reference-answer">
            <h3 class="section-title">参考答案</h3>
            <div>
              {{ questionList[currentQuestionIndex].referenceAnswer  }}
            </div>
            <h3 class="section-title">答案说明</h3>
            <el-input
              v-model="questionList[currentQuestionIndex].answerInfo"
              type="textarea"
              :rows="4"
              placeholder="请输入参考答案说明..."
            />
          </div>

          <el-form-item label="关联知识点">
            <el-input
              v-model="selectedKnowledgePointsText"
              placeholder="点击选择知识点"
              readonly
              style="cursor: pointer"
              @click="openKnowledgeSelectionDialog"
            />
          </el-form-item>

          <!-- 知识点选择弹窗 -->
          <el-dialog
            v-model="isKnowledgeDialogVisible"
            title="选择知识点"
            width="80%"
            :before-close="handleKnowledgeDialogClose"
          >
            <div class="knowledge-dialog-container">
              <!-- 顶部操作栏 -->
              <div class="dialog-header-actions" v-if="currentDialogView === 'list'">
                <el-button type="primary" @click="switchToAddKnowledge">
                  新增知识点
                </el-button>
              </div>

               <div class="dialog-header-actions" v-if="['add', 'edit'].includes(currentDialogView)">
                        <el-button @click="cancelAddKnowledge">取消</el-button>
                        <el-button type="primary" @click="submitNewKnowledge">提交</el-button>
               </div>

              <!-- 弹窗内容区 -->
              <div class="knowledge-selection-container">
                <!-- 左侧已选知识点 -->
                <div class="selected-knowledges">
                  <h3>已选知识点</h3>
                  <div v-if="selectedKnowledgePoints.length === 0" class="empty-tip">
                    暂无选中的知识点
                  </div>
                  <div v-else class="knowledge-list">
                    <div
                      v-for="point in selectedKnowledgePoints"
                      :key="point.id"
                      class="knowledge-item"
                    >
                      <span>{{ point.name }}</span>
                      <el-button
                        type="text"
                        icon="el-icon-delete"
                        @click="removeSelectedKnowledge(point.id)"
                      />
                    </div>
                  </div>
                </div>

                <!-- 右侧知识点列表/编辑区域 -->
                <div class="knowledge-content">
                  <div v-if="currentDialogView === 'list'">
                    <!-- 搜索区域 -->
                    <el-form :model="knowledgeSearchForm" class="knowledge-search-form">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <el-form-item label="知识点名称">
                            <el-input v-model="knowledgeSearchForm.name" placeholder="请输入知识点名称" />
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="科目">
                            <el-select v-model="knowledgeSearchForm.subject" placeholder="请选择科目">
                              <el-option label="数学" value="数学" />
                              <el-option label="英语" value="英语" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="年级">
                            <el-select v-model="knowledgeSearchForm.grade" placeholder="请选择年级">
                              <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade" />
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <el-form-item label="教材版本">
                            <el-input v-model="knowledgeSearchForm.textBook" placeholder="请输入教材版本" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <div class="search-actions">
                        <el-button type="primary" @click="searchKnowledges">搜索</el-button>
                        <el-button @click="resetKnowledgeSearch">重置</el-button>
                      </div>
                    </el-form>

                    <!-- 知识点列表 -->
                    <el-table
                      :data="knowledgeTableData"
                      border
                      stripe
                      :row-key="row => row.id"
                      @selection-change="handleKnowledgeSelectionChange"
                    >
                      <el-table-column type="selection" width="55" :selectable="isKnowledgeSelectable" />
                      <el-table-column prop="name" label="知识点名称" min-width="180" />
                      <el-table-column prop="grades" label="年级" width="120" />
                      <el-table-column prop="subject" label="科目" width="100" />
                      <el-table-column prop="area" label="地区" width="120" />
                    </el-table>

                    <!-- 分页区域 -->
                    <el-pagination
                      class="pagination"
                      :current-page="knowledgeCurrentPage"
                      :page-size="knowledgePageSize"
                      :total="knowledgeTotal"
                      @current-change="handleKnowledgePageChange"
                      @size-change="handleKnowledgeSizeChange"
                      layout="prev, pager, next, jumper"
                    />
                  </div>

                  <!-- 知识点编辑区域 -->
                  <div v-else-if="currentDialogView === 'edit'">
                    <div class="edit-container">
                      <el-form :model="newKnowledgeForm" label-width="120px" class="edit-form">
                        <el-form-item label="知识点名称">
                          <el-input v-model="newKnowledgeForm.name" />                        
                        </el-form-item>
                        <el-form-item label="年级">
                          <el-select v-model="newKnowledgeForm.grades" multiple placeholder="请选择年级">
                            <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade" />
                          </el-select>
                        </el-form-item>
                        <el-form-item label="科目">
                          <el-select v-model="newKnowledgeForm.subject" placeholder="请选择科目">
                            <el-option label="数学" value="数学" />
                            <el-option label="英语" value="英语" />
                          </el-select>
                        </el-form-item>
                        <el-form-item label="地区">
                          <el-cascader
                            v-model="newKnowledgeForm.area"
                            :options="areaOptions"
                            placeholder="请选择地区"
                            :props="{ expandTrigger: 'hover' }"
                          />
                        </el-form-item>
                        <el-form-item label="教材版本">
                          <el-input v-model="newKnowledgeForm.textBook" placeholder="请输入教材版本" />
                        </el-form-item>
                        <el-form-item label="简介">
                          <el-input v-model="newKnowledgeForm.briefIntroduction" type="textarea" :rows="2" placeholder="请输入简介" />
                        </el-form-item>
                        <el-form-item label="详细描述">
                          <el-input v-model="newKnowledgeForm.detailedDescription" type="textarea" :rows="3" placeholder="请输入详细描述" />
                        </el-form-item>
                        <el-form-item label="视频讲解">
                          <el-upload
                            class="video-upload"
                            action="#"
                            :on-success="handleVideoUpload"
                            :file-list="videoFileList"
                            accept="video/*"
                            :limit="1"
                          >
                            <el-button type="primary">上传视频</el-button>
                          </el-upload>
                        </el-form-item>
                        <el-form-item label="视频说明">
                          <el-input v-model="newKnowledgeForm.videoDescription" type="textarea" :rows="2" placeholder="请输入视频说明" />
                        </el-form-item>
                        <el-form-item label="关联知识点">
                          <el-select
                            v-model="newKnowledgeForm.relatedKnowledgeIds"
                            multiple
                            placeholder="请选择关联知识点"
                            style="width: 100%"
                          >
                            <el-option
                              v-for="knowledge in mockKnowledgeData"
                              :key="knowledge.id"
                              :label="knowledge.name"
                              :value="knowledge.id"
                              :disabled="false"
                            />
                          </el-select>
                        </el-form-item>
                      </el-form>

                     
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref, watch, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus';
import router from '../../router';
import { useRoute } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';

// 知识点选择弹窗相关状态
const isKnowledgeDialogVisible = ref(false);
const currentDialogView = ref('list'); // 'list' 或 'edit'
const selectedKnowledgePoints = ref([]);
const selectedKnowledgePointsText = ref('');
const knowledgeSearchForm = reactive({
  name: '',
  subject: '',
  grade: '',
  textBook: ''
});
const knowledgeTableData = ref([]);
const knowledgeCurrentPage = ref(1);
const knowledgePageSize = ref(10);
const knowledgeTotal = ref(0);
// 视频上传相关
const videoFileList = ref([]);
const handleVideoUpload = (response, file, fileList) => {
  // 模拟视频上传成功
  newKnowledgeForm.videoUrl = URL.createObjectURL(file.raw);
  videoFileList.value = fileList;
};

const newKnowledgeForm = reactive({
  name: '',
  grades: [],
  subject: '',
  area: ['安徽', '合肥'],
  textBook: '',
  briefIntroduction: '',
  detailedDescription: '',
  videoUrl: '',
  videoDescription: '',
  relatedKnowledgeIds: []
});

// 提前声明变量以解决初始化顺序问题
const gradeOptions = ref(['初一', '初二', '初三', '高一']);
const areaOptions = ref([{
  value: '安徽',
  label: '安徽',
  children: [{
    value: '合肥',
    label: '合肥'
  }]
}]);

// 模拟知识点数据
let mockKnowledgeData = Array.from({ length: 50 }, (_, i) => ({
  id: i + 1,
  name: `知识点${i + 1}`,
  grades: gradeOptions.value.slice(0, Math.ceil(Math.random() * 3)),
  subject: ['数学', '英语'][Math.floor(Math.random() * 2)],
  area: ['安徽', '合肥'],
  textBook: `教材版本${i % 3 + 1}`,
  briefIntroduction: `这是知识点${i + 1}的简介`,
  detailedDescription: `这是知识点${i + 1}的详细描述内容...`,
  videoUrl: i % 5 === 0 ? `https://example.com/video${i + 1}.mp4` : '',
  videoDescription: i % 5 === 0 ? `这是知识点${i + 1}的视频说明` : '',
  relatedKnowledgeIds: i > 1 ? [i] : []
}));

// 打开知识点选择弹窗
const openKnowledgeSelectionDialog = () => {
  // 初始化已选知识点
  const currentQuestion = questionList[currentQuestionIndex.value];
  if (currentQuestion.knowledgePoints && currentQuestion.knowledgePoints.length > 0) {
    selectedKnowledgePoints.value = mockKnowledgeData.filter(
      item => currentQuestion.knowledgePoints.includes(item.id)
    );
  } else {
    selectedKnowledgePoints.value = [];
  }
  updateSelectedKnowledgeText();
  currentDialogView.value = 'list';
  isKnowledgeDialogVisible.value = true;
  searchKnowledges();
};

// 更新已选知识点文本显示
const updateSelectedKnowledgeText = () => {
  selectedKnowledgePointsText.value = selectedKnowledgePoints.value
    .map(point => point.name)
    .join(', ');
};

// 关闭知识点选择弹窗
const handleKnowledgeDialogClose = () => {
  // 保存选择的知识点到当前题目
  const currentQuestion = questionList[currentQuestionIndex.value];
  currentQuestion.knowledgePoints = selectedKnowledgePoints.value.map(point => point.id);
  isKnowledgeDialogVisible.value = false;
};

// 切换到新增知识点视图
const switchToAddKnowledge = () => {
  // 重置新增知识点表单
  Object.keys(newKnowledgeForm).forEach(key => {
    if (key === 'grades') {
      newKnowledgeForm[key] = [];
    } else if (key === 'area') {
      newKnowledgeForm[key] = ['安徽', '合肥'];
    } else {
      newKnowledgeForm[key] = '';
    }
  });
  currentDialogView.value = 'edit';
};

// 取消新增知识点
const cancelAddKnowledge = () => {
  currentDialogView.value = 'list';
};

// 提交新增知识点
const submitNewKnowledge = () => {
  if (!newKnowledgeForm.name) {
    ElMessage.error('知识点名称不能为空');
    return;
  }

  // 创建新知识点
  const newId = mockKnowledgeData.length + 1;
  const newKnowledge = {
    id: newId,
    name: newKnowledgeForm.name,
    grades: newKnowledgeForm.grades,
    subject: newKnowledgeForm.subject,
    area: newKnowledgeForm.area,
    textBook: newKnowledgeForm.textBook,
    briefIntroduction: newKnowledgeForm.briefIntroduction,
    detailedDescription: newKnowledgeForm.detailedDescription,
    videoUrl: newKnowledgeForm.videoUrl,
    videoDescription: newKnowledgeForm.videoDescription,
    relatedKnowledgeIds: newKnowledgeForm.relatedKnowledgeIds
  };

  // 添加到模拟数据
  mockKnowledgeData.push(newKnowledge);

  // 自动选择新添加的知识点
  selectedKnowledgePoints.value.push(newKnowledge);
  updateSelectedKnowledgeText();

  ElMessage.success('知识点添加成功');
  currentDialogView.value = 'list';
  searchKnowledges(); // 刷新列表
};

// 搜索知识点
const searchKnowledges = () => {
  // 模拟过滤数据
  const filtered = mockKnowledgeData.filter(item => {
    return item.name.includes(knowledgeSearchForm.name) &&
      (knowledgeSearchForm.subject ? item.subject === knowledgeSearchForm.subject : true) &&
      (knowledgeSearchForm.grade ? item.grades.includes(knowledgeSearchForm.grade) : true) &&
      (knowledgeSearchForm.textBook ? item.textBook.includes(knowledgeSearchForm.textBook) : true);
  });

  knowledgeTotal.value = filtered.length;
  knowledgeTableData.value = filtered.slice(
    (knowledgeCurrentPage.value - 1) * knowledgePageSize.value,
    knowledgeCurrentPage.value * knowledgePageSize.value
  );
};

// 重置知识点搜索
const resetKnowledgeSearch = () => {
  knowledgeSearchForm.name = '';
  knowledgeSearchForm.subject = '';
  knowledgeSearchForm.grade = '';
  knowledgeSearchForm.textBook = '';
  knowledgeCurrentPage.value = 1;
  searchKnowledges();
};

// 知识点分页变化
const handleKnowledgePageChange = (page) => {
  knowledgeCurrentPage.value = page;
  searchKnowledges();
};

const handleKnowledgeSizeChange = (size) => {
  knowledgePageSize.value = size;
  knowledgeCurrentPage.value = 1;
  searchKnowledges();
};

// 知识点选择变化
const handleKnowledgeSelectionChange = (val) => {
  // 添加选中的知识点
  val.forEach(item => {
    if (!selectedKnowledgePoints.value.some(p => p.id === item.id)) {
      selectedKnowledgePoints.value.push(item);
    }
  });
  updateSelectedKnowledgeText();
};

// 检查知识点是否可选择
const isKnowledgeSelectable = (row) => {
  return !selectedKnowledgePoints.value.some(p => p.id === row.id);
};

// 移除已选知识点
const removeSelectedKnowledge = (id) => {
  selectedKnowledgePoints.value = selectedKnowledgePoints.value.filter(p => p.id !== id);
  updateSelectedKnowledgeText();
};

// 初始导入代码
const currentQuestionType = ref('choice')

const route = useRoute();
// 题目模版
const questionTemplate = {
  name: '', // 题目题干
  description: '', // 题目描述
  type: 'choice',
  options: [
    { label: '选项A', value: 'A' },
    { label: '选项B', value: 'B' },
    { label: '选项C', value: 'C' },
    { label: '选项D', value: 'D' }
  ],
  isMultiple: false,
  singleAnswer: null,   // 单选答案
  multipleAnswers: [],   // 多选答案（改为数组存储）
  referenceAnswer: '',   // 参考答案
  answerInfo: '',        // 答案解析
  knowledgePoints: []  // 新增：关联知识点数组
};
const question = reactive({
  ...questionTemplate
});

const questionList = reactive([
  question
]);


// 获取所有的问题
async function getQuestions () {
   const ids = (route.query.id || '').join(',');
   // api 获取接口 -- questionList --- 重新赋值
}



let currentQuestionIndex = ref(0);


// 新增一个题目
function addQuestion() {
  if (currentQuestionIndex < questionList.length - 1) {
    currentQuestionIndex.value  =  currentQuestionIndex.value + 1;
    return;
  }
  
  currentQuestionIndex.value  =  currentQuestionIndex.value + 1;
  // 复制当前题目模版并添加到列表中
  questionList.push({ ...questionTemplate, type: questionList[currentQuestionIndex.value - 1].type });
}

// 监听题型切换
watch(() => question.isMultiple, (newVal) => {
  if (newVal) {
    question.singleAnswer = null
  } else {
    question.multipleAnswers = []
  }
});





const abcArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
// 添加选项时生成唯一ID
const addOption = () => {
  if (question.options.length >= abcArr.length) {
    return
  };
  question.options.forEach((item, index) => {
    item.label = `选项${abcArr[index]}`;
    item.value = abcArr[index];
  })
  question.options.push({
    label: `选项${abcArr[question.options.length]}`,
    id: Date.now() + question.options.length, // 唯一标识
    value: abcArr[question.options.length] // 选项字母
  })
}

// 删除选项
const removeOption = (index) => {
  question.options.splice(index, 1);
  question.options.forEach((item, index) => {
    item.label = `选项${abcArr[index]}`;
    item.value = abcArr[index];
  })
};

// 实现 handleSave 方法
const handleSave = () => {
  // 验证科目选择弹窗是三个是否是否有值，没有纸提示 科目选择- 什么
  // 验证科目选择弹窗三个选择器是否有值
  if (!selectedArea.value || selectedArea.value.length === 0) {
    ElMessage.error('科目选择 - 地区未选择');
    return;
  }
  if (!selectedGrade.value) {
    ElMessage.error('科目选择 - 年级未选择');
    return;
  }
  if (!selectedSubject.value) {
    ElMessage.error('科目选择 - 科目未选择');
    return;
  }

  for (let i = 0; i < questionList.length; i++) {
    const question = questionList[i];
    
    // 验证题目题干是否必填
    if (!question.name.trim()) {
      ElMessage.error(`第 ${i + 1} 题的题干不能为空`);
      return;
    }

    // 如果是选择题，验证选项和参考答案
    if (question.type === 'choice') {
      // 验证选项是否有值
      for (let j = 0; j < question.options.length; j++) {
        if (!question.options[j].label.trim()) {
          ElMessage.error(`第 ${i + 1} 题的选项 ${String.fromCharCode(65 + j)} 不能为空`);
          return;
        }
      }

      // 验证是否有参考答案
      if (!question.referenceAnswer) {
        ElMessage.error(`第 ${i + 1} 题必须设置参考答案`);
        return;
      }
    }
  }

  // 验证通过，执行保存逻辑
  ElMessage.success('题目保存成功');
  // 这里可添加实际的保存请求代码，例如：
  // saveQuestionApi(questionList).then(() => { /* 处理响应 */ });
};



// 新增：监听答案变化并同步到referenceAnswer
watch([() => question.singleAnswer, () => question.multipleAnswers], ([single, multiple]) => {
  if (question.isMultiple) {
    // 多选时格式化为逗号分隔的字符串（如"A,B,C"）
    question.referenceAnswer = multiple.join(',');
  } else {
    // 单选时直接使用选中值
    question.referenceAnswer = single || '';
  }
}, { immediate: true }); // 初始时执行一次


// 新增科目选择相关状态
const isChooseSubjectVisible = ref(false)  // 控制弹窗显示
const selectedArea = ref(['安徽', '合肥'])  // 省市级联选中值（默认安徽-合肥）
const selectedGrade = ref('初一')          // 年级选中值（默认初一）
const selectedSubject = ref('数学')         // 科目选中值（默认数学）

// 级联数据和年级选项已在文件上方声明
// const areaOptions = ref([...])
// const gradeOptions = ref([...])

// 科目选项（当前只有数学）
const subjectOptions = ref(['数学'])

// 打开科目选择弹窗
const chooseSuject = () => {
  isChooseSubjectVisible.value = true
}

// 关闭弹窗时的回调（可选）
const handleDialogClose = () => {
  isChooseSubjectVisible.value = false
}
// 新增知识点相关状态
const knowledgePoints = ref([])       // 当前可选知识点列表
const knowledgePointsLoading = ref(false)  // 加载状态

// 模拟知识点接口（实际应替换为真实API）
const fetchKnowledgePoints = async (area, grade, subject, keyword) => {
  knowledgePointsLoading.value = true
  // 模拟根据地区/年级/科目过滤的知识点数据
  const mockData = [
    { id: 1, name: '一元一次方程', area: '安徽-合肥', grade: '初一', subject: '数学' },
    { id: 2, name: '平行线性质', area: '安徽-合肥', grade: '初一', subject: '数学' },
    { id: 3, name: '三角形全等', area: '安徽-合肥', grade: '初二', subject: '数学' }
  ]
  // 过滤逻辑（实际应通过API实现）
  knowledgePoints.value = mockData.filter(item => 
    item.area === `${area[0]}-${area[1]}` &&
    item.grade === grade &&
    item.subject === subject &&
    item.name.includes(keyword)
  )
  knowledgePointsLoading.value = false
}

// 处理远程搜索
const handleRemoteSearch = (keyword) => {
  if (selectedArea.value?.length && selectedGrade.value && selectedSubject.value) {
    fetchKnowledgePoints(
      selectedArea.value, 
      selectedGrade.value, 
      selectedSubject.value, 
      keyword
    )
  }
}

// 监听科目选择变化，刷新知识点
watch([selectedArea, selectedGrade, selectedSubject], () => {
  handleRemoteSearch('')  // 初始加载无关键词
})

// 初始化 questionList
onMounted(() => {
  if (route.query.mode === 'edit') {
    getQuestions()
  }
})
</script>

<style>
 .options-list .el-radio-group {
  flex-direction: column;
}
  /* 知识点选择弹窗样式 */
  .knowledge-dialog-container {
    height: 70vh;
    display: flex;
    flex-direction: column;
  }

  .dialog-header-actions {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .knowledge-selection-container {
    display: flex;
    flex: 1;
    gap: 20px;
    overflow: hidden;
  }

  /* 视频上传样式 */
  .video-upload {
    margin-bottom: 20px;
  }

  /* 富文本编辑器样式 */
  .el-textarea {
    margin-bottom: 20px;
  }

  .selected-knowledges {
    width: 30%;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
  }

  .selected-knowledges h3 {
    padding: 10px 16px;
    border-bottom: 1px solid #e6e6e6;
    margin: 0;
    font-size: 14px;
    font-weight: bold;
  }

  .empty-tip {
    padding: 20px;
    text-align: center;
    color: #999;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .knowledge-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
  }

  .knowledge-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 10px;
    margin-bottom: 6px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .knowledge-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    overflow: hidden;
  }

  .knowledge-search-form {
    padding: 16px;
    border-bottom: 1px solid #e6e6e6;
    background: #f8f9fa;
  }

  .search-actions {
    display: flex;
    gap: 8px;
    padding-top: 10px;
  }

  .el-table {
    flex: 1;
    overflow-y: auto;
  }

  .pagination {
    padding: 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #e6e6e6;
  }

  /* 知识点编辑区域样式 */
  .edit-container {
    padding: 16px;
    display: flex;
    flex-direction: column;
    height: 100%;

    overflow-y: auto; /* 添加垂直滚动 */
  }

  .edit-form {
    flex: 1;
    overflow-y: auto;
  }

  .form-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 16px;
    padding-top: 16px;
    border-top: 1px solid #e6e6e6;
  }

</style>

<style scoped lang="scss">
.home {
  .operate-bar {
    margin-bottom: 16px;
    
    .button-group-end {
      display: flex;
      justify-content: flex-end;
      
      .el-button + .el-button {
        margin-left: 8px;
      }
    }

    .button-group-start {
      display: flex;
      justify-content: flex-start; 
    }
  }

  .main-layout {
    margin: 0 -10px;
  }

  .question-type-card {
    margin-bottom: 20px;
    
    .card-title {
      font-weight: 600;
      font-size: 16px;
    }
  }

  .question-config-card {
    .base-config {
      margin-bottom: 24px;
      .steps {
        display: flex;
        justify-content: space-between;
        margin-bottom: 16px;
      }
    }
    
    .section-title {
      margin-bottom: 16px;
      font-size: 16px;
      color: #333;
    }
  }

  .choice-options {
    .options-list {
      margin-bottom: 16px;
    }

    .option-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      
      .option-selector {
        margin-right: 8px;
        min-width: 40px;
      }

      .option-input {
        flex: 1;
        margin: 0 8px;
        
        :deep(.el-input-group__prepend) {
          padding: 0 8px;
          background-color: #f5f7fa;
        }
      }

      .delete-btn {
        flex-shrink: 0;
      }
    }

    .option-actions {
      display: flex;
      align-items: center;
      margin-top: 16px;
      
      .el-radio-group {
        margin-left: 16px;
      }
    }
  }

  /* 垂直Tab样式 */
  :deep(.vertical-tabs) {
    .el-tabs__item {
      padding: 8px 16px !important;
      height: auto;
      line-height: 1.5;
      text-align: right;
    }
    
    .el-tabs__nav-wrap::after {
      display: none;
    }
  }
}
</style>

